<template>
  <div>
    <h1>{{ mes }}</h1>
    <el-row>
      <el-col :span="21" :offset="1">
        <el-form :model="residentForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-row>
            <el-col :span="8">
              <el-form-item sty label="姓名：" prop="name">
                <el-input v-model="residentForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号：" prop="card">
                <el-input v-model="residentForm.card" @blur="valCard(this.residentForm.card)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="支付方式：" prop="buyTime">
                <el-select v-model="residentForm.paymentId" placeholder="请选择">
                  <el-option v-for="item in payments" :key="item.id" :label="item.paymentMethod" :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="联系电话1：" prop="phone1">
                <el-input v-model="residentForm.phone1" @blur="valPhone1(residentForm.phone1)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="联系电话2：">
                <el-input v-model="residentForm.phone2" @blur="valPhone2(residentForm.phone2)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="住址：" prop="buildingId">
                <el-select style="width: 120px" v-model="residentForm.buildingId" @change="selectAllUnit()"
                           placeholder="请选择楼栋">
                  <el-option
                      v-for="building in building"
                      :key="building.id"
                      :label="building.buildingName"
                      :value="building.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="40px" prop="unitId">
                <el-select style="width: 130px" v-model="residentForm.unitId" @change="selectAllHouse()"
                           placeholder="请选择单元号">
                  <el-option
                      v-for="item in unit"
                      :key="item.id"
                      :label="item.unitName"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label-width="40px" prop="houseId">
                <el-select style="width: 130px" v-model="residentForm.houseId" placeholder="请选择门牌号">
                  <el-option
                      v-for="item in house"
                      :key="item.id"
                      :label="item.houseNumber"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="籍贯：" prop="nativePlace">
                <el-input v-model="residentForm.nativePlace" @blur="valNativePlace(residentForm.nativePlace)"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="车位：" label-width="110px">
<!--                需要检查备选车位是否有人-->
                <el-select v-model="residentForm.parkingId" @change="checkParking()"
                           placeholder="请选择车位">
                  <el-option v-for="item in parkings"
                             :key="item.id"
                             :label="item.spaceNumber"
                             :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
                <el-form-item prop="personSize" label="居民类型：">
                  <el-select v-model="residentForm.residentTypeId" placeholder="请选择居民类型">
                    <el-option v-for="item in residentTypes"
                        :key="item.id"
                        :label="item.type"
                        :value="item.id"
                    />
                  </el-select>
                </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="紧急联系人：">
                <el-input v-model="residentForm.emergencyPerson"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="紧急电话1：">
                <el-input v-model="residentForm.emergencyPhone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="1">
              <el-form-item label="紧急电话2：">
                <el-input v-model="residentForm.emergencyPhone2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="邮箱：">
                <el-input v-model="residentForm.email"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="身份证正面照片：" label-width="85px">
                <el-upload
                    class="upload-demo"
                    :headers="manageToken"
                    action="http://localhost:8080/manage/uploadCardPicFacade"
                    :on-success="handleCardFacadeSuccess"
                    :on-remove="handleRemove"
                    :file-list="cardFileList"
                    :before-upload="beforeUpload"
                    list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="身份证反面照片：" label-width="85px">
                <el-upload
                    class="upload-demo"
                    :headers="manageToken"
                    action="http://localhost:8080/manage/uploadCardPicBack"
                    :on-success="handleCardBackSuccess"
                    :on-remove="handleRemove"
                    :file-list="cardFileList"
                    list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="居民照片：" label-width="85px">
                <el-upload
                    class="upload-demo"
                    :headers="manageToken"
                    action="http://localhost:8080/manage/uploadPic"
                    :on-success="handlePictureSuccess"
                    :on-remove="handleRemove"
                    :file-list="cardFileList"
                    list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" :offset="7">
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                &nbsp;
                <el-button @click="resetForm('ruleForm')">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-col>
    </el-row>
  </div>
</template>

<script>
let id = 0;
export default {
    data() {
      return {
        mes:"添加居民",
        residentForm: {
          id: '',
          name: '',
          card: '',
          cardPicFacade: '',//身份证正面
          cardPicBack: '',//身份证反面
          picture: '',
          phone1: '',
          phone2: '',
          emergencyPerson: '',
          emergencyPhone: '',
          emergencyPhone2: '',
          nativePlace: '',
          staffId: '',
          email: '',
          unitId: '',
          buildingId: '',
          houseId: '',
          parkingId:'',
          paymentId:'',
          residentTypeId:'',
        },
        manageToken: {
          manageToken: window.localStorage.getItem("manageToken")
        },
        staff: JSON.parse(window.localStorage.getItem("admin")),
        building: [],
        unit: [],
        house:[],
        payments:[],
        parkings:[],
        residentTypes:[],
        uploadAction: null,
        houseId:null,
        cardFileList: [],
        allowedExts: ".jpg,.png",
        imgUrl: '',
        rules: {
            name: [
              {required: true, message: '请输入姓名', trigger: 'blur'},
              {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
            ],
            card: [
              {required: true, message: '请输入身份证', trigger: 'blur'},
              {min:18,max:18,message:'请输入18位身份证',trigger:'blur'},
            ],
            phone1: [
              {required: true, message: '请输入手机号', trigger: 'blur'},
            ],
            phone2:[
              {required: true, message: '请输入手机号', trigger: 'blur'},
            ],
            buildingId: [
              {required: true, message: '请选择楼栋', trigger: 'change'},
            ],
            unitId: [
              {required: true, message: '请选择单元', trigger: 'change'},
            ],
            houseId:[
              {required: true, message: '请选择门牌号', trigger: 'change'},
            ],
            nativePlace: [
              {required: true, message: '请填写籍贯', trigger: 'blur'},
            ],
            personSize: [
              {required: true, message: '请填写人数', trigger: 'blur'},

            ]
          },
        cardMsg:false,
        phone1Msg:false,
        phone2Msg:false,
        nativePlaceMsg:false,
        houseMsg:false,
        unitMsg:false,
        buildingMsg:false,
        residentTypeMsg:false,
        };
    },
  created() {
    this.selectAllBuilding();
    this.selectAllPayment();
    this.selectAllParking();
    this.selectAllResidentType();
    if (this.$route.query.id!=null){
      this.mes="修改居民";
      this.getResidentById(this.$route.query.id);
    }
  },
    methods: {
      valHouse(){
        if (this.residentForm.houseId==null||this.residentForm.houseId==''){
          this.$message.error("请选择门牌号");
          this.houseMsg=false
        }else{
          this.houseMsg=true;
        }
      },
      valUnit(){
        if (this.residentForm.unitId==null||this.residentForm.unitId==''){
          this.$message.error("请选择单元号")
          this.unitMsg = false;
        }else{
          this.unitMsg= true;
        }
      },
      valResidentType(){
        if (this.residentForm.residentTypeId==null||this.residentForm.residentTypeId==''){
          this.$message.error("请选择住户类型")
          this.residentTypeMsg = false;
        }else{
          this.residentTypeMsg= true;
        }
      },
      valBuilding(){
        if (this.residentForm.buildingId==null||this.residentForm.buildingId==''){
          this.$message.error("请选择楼栋号")
          this.buildingMsg = false;
        }else{
          this.buildingMsg= true;
        }
      },
      valCard(card){
        var exp = /^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}([0-9]|X)$/;
        this.cardMsg = exp.test(card);
      },
      valPhone1(phone1){
        var exp = /^1[3-9]\d{9}$/;
        this. phone1Msg = exp.test(phone1);
      },
      valPhone2(phone2){
        var exp = /^1[3-9]\d{9}$/;
        this. phone2Msg = exp.test(phone2);
      },
      valNativePlace(nativePlace){
        if (nativePlace==null||nativePlace==''){
          this.nativePlaceMsg = false;
          this.$message.error("请输入籍贯");
        }
        else{
          this.nativePlaceMsg = true;
        }
      },
      submitForm(formName) {
        this.residentForm.staffId = this.staff.id
        this.valCard(this.residentForm.card);
        this.valPhone1(this.residentForm.phone1)
        this.valPhone2(this.residentForm.phone2)
        this.valNativePlace(this.residentForm.nativePlace);
        this.valBuilding();
        this.valUnit();
        this.valHouse();
        this.valResidentType();
        if (this.cardMsg && this.phone1Msg && this.phone2Msg && this.nativePlaceMsg && this.buildingMsg && this.unitMsg && this.houseMsg && this.residentTypeMsg){
          this.$axios.post("manage/insertResident", this.residentForm,{params:{houseId:this.houseId}})
              .then(response => {
                //判断是否有异常
                if (response.data.code === 9999) {
                  this.$message({
                    showClose: true,
                    message: '身份证格式错误',
                    type: 'error',
                  });
                } else {
                  this.$refs[formName].resetFields();
                  this.$message({
                    showClose: true,
                    message: '添加成功',
                    type: 'success',
                  });
                }
              })
        }else if(this.cardMsg==false){
          this.$message.error("身份证输入不合法")
        }else if(this.nativePlaceMsg == false){
          this.$message.error("籍贯不能为空")
        }else if (this.phone1Msg==false){
          this.$message.error("手机号输入不合法")
        }else if (this.phone2Msg == false){
          this.$message.error("联系方式输入不合法")
        }
      },

      getResidentById(id){
        this.$axios.get("manage/getResidentById",{params:{id:id}}).then(res=>{
            this.residentForm = res.data.resident;
            this.houseId = this.residentForm.houseId;
            this.selectAllUnit();
            this.selectAllHouse();
            console.log(this.residentForm);
        });
      },
      checkParking(){
        if (this.residentForm.parkingId==null||this.residentForm.parkingId==''){
          return;
        }
        else{
          this.$axios.get("manage/checkParking",{params:{id:this.residentForm.parkingId}}).then(res=>{
            if (res.data.count>0){
              this.$confirm('已有用户拥有该车位是否继续添加', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$message({
                  type: 'success',
                  message: '已添加!'
                });
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消'
                });
                this.residentForm.parkingId=null;
              });
            }
          });
        }
      },
      //查询所有支付方式
      selectAllPayment(){
        this.$axios.get("manage/findAllPayment").then(res=>{
          this.payments = res.data.data;
        });
      },
      //查询所有车位
      selectAllParking(){
         // this.$axios.get("manage/findAllParking").then(res=>{
         //   this.parkings = res.data.parkings;
         // });
      },
      selectAllResidentType(){
        this.$axios.get("manage/findAllResidentType").then(res=>{
          this.residentTypes = res.data.residentTypes;
        })
      },
      selectAllBuilding() {
        this.$axios.get("manage/selectAllBuilding")
            .then(response => {
              this.building = response.data.data;
            })
      },
      selectAllUnit() {
        this.$axios.get("manage/unit/selectUnitById", {params: {id: this.residentForm.buildingId}})
            .then(response => {
              this.unit = response.data.data;
            })
      },
      selectAllHouse(){
        this.$axios.get("manage/selectHouseById",{params:{id:this.residentForm.unitId}}).then(res=>{
          this.house = res.data.house;
        })
      },
      // checkPersonSizeCount(){
      //   if (this.residentForm.personSize > this.personSize){
      //     return true;
      //   }
      //   if (this.residentForm.personSize <= this.personSize){
      //     return false;
      //   }
      // },

      resetForm(form){
        this.$refs[form].resetFields();
      },
      handleCardFacadeSuccess(res, file) {
        this.residentForm.cardPicFacade = res.fileName;
      },
      handleCardBackSuccess(res, file) {
        this.residentForm.cardPicBack = res.fileName;
      },
      handlePictureSuccess(res, file) {
        this.residentForm.picture = res.fileName;
      },
      handleRemove() {
      },
      beforeUpload(file) {
        let dotIndex = file.name.lastIndexOf(".");

        if (dotIndex == -1) {
          this.$message.error('只能上传图片(' + this.allowedExts + ')');
          return false;
        }
        //扩展名
        let ext = file.name.substring(dotIndex);
        if (!("," + this.allowedExts + ",").includes("," + ext + ",")) {
          this.$message.error('只能上传图片(' + this.allowedExts + ')');
          return false;
        }

        const isLt2M = file.size / 1024 / 1024 < 2;

        if (file.size > 1024 * 1024 * 2) {
          this.$message.error('上传头像图片大小不能超过 2M!');
          return false;
        }
        return true;
      }
    },
}
</script>

<style scoped>

</style>
